declare var amdRequire: any;

namespace feng3d
{
    var list = [
        "sdf.glsl",
        "rmshadows.glsl",
        "distfunctions.glsl",
        "impact.glsl",
        "snail.glsl",
    ];

    var monacoEditor: monaco.editor.IStandaloneCodeEditor;
    var shadertoy = new ShaderToy();
    var select: HTMLSelectElement;

    initMonaco(() =>
    {
        initlist();
        showShader();
    });

    function initlist()
    {
        select = document.getElementById("select") as HTMLSelectElement;

        list.forEach(i =>
        {
            var option = document.createElement("option");
            option.value = i;
            option.appendChild(document.createTextNode(i));
            select.appendChild(option);
        });
        select.onchange = showShader;
    }

    function showShader()
    {
        var shaderPath = `shaders/${select.options[select.selectedIndex].value}`;

        loader.loadText(shaderPath, (code) =>
        {
            shadertoy.setShaderCode(code);
            showCode(code);
        });
    }

    function initMonaco(callback: () => void)
    {
        //
        amdRequire.config({ paths: { 'vs': 'libs/monaco-editor/min/vs' } });
        amdRequire(['vs/editor/editor.main'], () =>
        {
            monacoEditor = monaco.editor.create(document.getElementById('container'), {
                model: null,
                formatOnType: true,
            });
            window.onresize = function ()
            {
                monacoEditor.layout();
            };
            callback();
        });
    }

    function showCode(code: string)
    {

        var oldModel = monacoEditor.getModel();
        var newModel = monaco.editor.createModel(code, "glsl");
        monacoEditor.setModel(newModel);
        if (oldModel) oldModel.dispose();

        monacoEditor.onDidChangeModelContent(() =>
        {
            var newcode = monacoEditor.getValue();
            shadertoy.setShaderCode(newcode);
        });
    };

}